package com.fun._多线程RPC;

import java.util.ArrayList;
import java.util.concurrent.ExecutorService;

import static java.util.concurrent.Executors.newFixedThreadPool;

/**
 * @author liyiruo
 * @Description 预先有一个集合，里面有10万条数据
 * 每条数据轮流去rpc请求，获取结果后将数据存入数据库
 * @Date 2021/3/22 上午10:02
 */
public class _多线程RPC implements Runnable {

    final static Integer cap = 100000;
    volatile static ArrayList<Integer> list = new ArrayList(cap);

    static {
        for (int i = 0; i < cap; i++) {
            list.add(i, i);
        }
    }


    public static void main(String[] args) {
        //final ReentrantLock lock = this.lock;
        long start = System.currentTimeMillis();
        System.out.println("开始时间：" + start);
        //_多线程RPC rpc = new _多线程RPC();

      /*  while (list.size()>0) {
            exRun(rpc);
        }*/

        MyService service = new MyService();
        while (true){

            if (MyService.index==MyService.cap-1){
                break;
            }
            System.out.println("index=>"+MyService.index);
            exRun(service);
        }
        long end = System.currentTimeMillis();
        System.out.println("结束时间：" + end);
        System.out.println("耗时：" + (end - start));
    }

    /**
     * rpc 调用 假设这个是远程调用
     *
     * @param s
     * @return
     */
    public static String rpc(String s) {
        String name = Thread.currentThread().getName();
        long id = Thread.currentThread().getId();
        return "线程名称：" + name + "线程ID " + id + "传入参数：" + s;
    }
    /**
     * 获取一个list
     *
     * @return
     */
    public static synchronized Integer getListValue() {
        Integer lastValue = list.remove(list.size() - 1);
        return lastValue;
    }


    @Override
    public void run() {
        if (_多线程RPC.list.size() > 0) {
            System.out.println("==>"+list.get(list.size()-1));
            list.remove(list.size() - 1);
            long l = System.currentTimeMillis();
            String rpc = rpc(String.valueOf(l));
            System.out.println(rpc);
        }
    }

    //线程池执行方法
    public static void exRun(Runnable runnable) {
        ExecutorService fixedThreadPool = newFixedThreadPool(12);
        //使用for循环创建线程，其实最终 只使用了一个线程。
        for (int i = 0; i < 50; i++) {
            fixedThreadPool.execute(runnable);
        }
        //fixedThreadPool.execute(runnable);
        fixedThreadPool.shutdown();
    }

}
